package com.murray.shop.background.controller;

import com.murray.shop.background.pojo.Admin;
import com.murray.shop.background.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * @author Murray
 * @Date 2021/8/19
 * @Time 23:30
 * @Description 处理管理员的请求
 */
@Controller
@RequestMapping(value = "/admin")
public class AdminController {

    @Autowired
    AdminService adminService;

    /**
     * 处理登录请求
     *
     * @return 到登录页面
     */
    @RequestMapping(value = "/loginPage")
    public String login() {
        return "login";
    }

    @RequestMapping(value = "/loginReq", method = RequestMethod.GET)
    public ModelAndView loginReq(Admin admin, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        //判断用户是否登录成功，成功返回一个对象否则null
        Admin admin1 = adminService.loginReq(admin);
        System.out.println(admin1);
        if (admin1 != null) {
            session.setAttribute("admin", admin1);
            //登录成功
            modelAndView.addObject("admin", admin1);
            modelAndView.setViewName("index");
            return modelAndView;
        }
        modelAndView.setViewName("login");
        modelAndView.addObject("error", "用户名或者密码错误！");
        return modelAndView;
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        if (session.getAttribute("admin") != null) {
            session.removeAttribute("admin");
        }
        return "login";
    }

}
